package admin

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type OrderController struct{}

// Index 订单列表
func (ctrl *OrderController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	status := c.Query("status")
	orderType := c.Query("type")

	var orders []models.Order
	var total int64

	db := config.DB.Model(&models.Order{}).Preload("User")

	if status != "" {
		db = db.Where("status = ?", status)
	}
	if orderType != "" {
		db = db.Where("type = ?", orderType)
	}

	db.Count(&total)
	db.Order("id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&orders)

	utils.Success(c, models.PageResponse{
		List:     orders,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Detail 订单详情
func (ctrl *OrderController) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var order models.Order
	if err := config.DB.Preload("User").First(&order, id).Error; err != nil {
		utils.Error(c, "订单不存在")
		return
	}

	utils.Success(c, order)
}

// Statistics 统计
func (ctrl *OrderController) Statistics(c *gin.Context) {
	var totalCount int64
	var paidCount int64
	var totalAmount float64

	config.DB.Model(&models.Order{}).Count(&totalCount)
	config.DB.Model(&models.Order{}).Where("status = ?", "已支付").Count(&paidCount)
	config.DB.Model(&models.Order{}).Where("status = ?", "已支付").
		Select("COALESCE(SUM(amount), 0)").Scan(&totalAmount)

	utils.Success(c, gin.H{
		"total_count":  totalCount,
		"paid_count":   paidCount,
		"total_amount": totalAmount,
	})
}
